package com.yeswater.rabbitmq_spingboot.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Author : yeswater
 */

@Slf4j
@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 把当前类注入到 RabbitTemplate
    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    /**
     * 交换机确认回调方法
     *
     * @param correlationData 保存回调消息的 ID 及相关信息
     * @param ack             true | false
     * @param cause           null | 原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String id = correlationData != null ? correlationData.getId() : null;
        if (ack) {
            log.info("交换机已经收到 ID 为 {}的消息", id);
        } else {
            log.info("交换机没有收到 ID 为 {}的消息,原因 : {}", id, cause);
        }
    }

    /**
     * 消息到不了消费者 进行回退
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.error("\n 消息 {} \n 交换机 {} \n 退回原因 {} \n 路由key {}", new String(message.getBody()), exchange, replyText, routingKey);
    }
}
